<template>
  <div>
    <!-- 
      树形菜单渲染,需要的条件
      1. 数据中必须有 childrdn 这个树形
      2. 必须设置 row-key

      expand-row-keys
        需要默认展开的行,是一个数组,这个数组中放需要默认展开行的id,这个id是 row-key 设置的属性

      row-key
        设置当前行数据的唯一标识,一般使用id
    -->
    <el-table
      border
      style="margin-bottom: 20px"
      :data="menuPermissionList"
      :expand-row-keys="expandKeys"
      row-key="id"
    >
      <el-table-column prop="name" label="名称"> </el-table-column>
      <el-table-column prop="code" label="权限值"> </el-table-column>
      <el-table-column prop="address" label="跳转权限"> </el-table-column>

      <el-table-column label="操作" >
        <template slot-scope="{row}">
          <el-button :title="getAddTitle(row.level)" type="primary" size="mini" title="添加菜单" icon="el-icon-plus" :disabled="row.level === 4" @click="toAddPermission(row)"></el-button>
          <el-button type="primary" size="mini" title="修改菜单" icon="el-icon-edit-outline" :disabled="row.level === 1" @click="toUpdatePermission(row)"></el-button>
          <el-button type="danger" size="mini" title="删除" icon="el-icon-delete" :disabled="row.level === 1" @click="removePermission(row)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 修改/添加菜单 -->
    <el-dialog
      :visible.sync="dialogPermissionVisible"
      :title="dialogTitle"
      @close="resetData"
    >
      <el-form
        label-width="120px"
        ref="permission"
        :model="permission"
        :rules="permissionRules"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="permission.name" />
        </el-form-item>

        <el-form-item label="功能权限值" prop="code">
          <el-input v-model="permission.code" />
        </el-form-item>

        <el-form-item label="跳转路由权限值" prop="toCode" v-if="permission.level === 4">
          <el-input v-model="permission.toCode" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetData">取 消</el-button>
        <el-button type="primary" @click="addOrUpdatePermission">确 定</el-button>
      </div>
    </el-dialog>
    
  </div>
</template>

<script>
import permissionApi from "@/api/acl/permission";
import { Message } from 'element-ui';

// 菜单权限校验的规则
const menuRules = {
  name: [{ required: true, message: "名称必须输入" }],
  code: [{ required: true, message: "权限值必须输入" }],
};
// 按钮功能权限校验的规则
const btnRules = {
  name: [{ required: true, message: "名称必须输入" }],
  code: [{ required: true, trigger: "blur", message: "功能权限值必须输入" }],
};

export default {
  name: 'PermissionList',
  data() {
    return {
      menuPermissionList: [], //菜单的列表
      expandKeys: [], // 需要自动展开的项
      dialogPermissionVisible: false, //控制dialog的显示与隐藏
      permission: {
        // 要操作的菜单权限对象
        level: 0,
        name: "",
        code: "",
        toCode: "",
      },
    };
  },
  computed: {
    //动态计算添加功能的标题是什么
    dialogTitle() {
      const { id, level } = this.permission;
      if (id) {
        return level === 4 ? "修改功能" : "修改菜单";
      } else {
        return level === 4 ? "添加功能" : "添加菜单";
      }
    },
    //根据权限等级来确定校验规则
    permissionRules() {
      return this.permission.level === 4 ? btnRules : menuRules;
    },
  },
  methods: {
    /* 请求获取菜单权限的列表 */
    async fetchPermissionList() {
      try {
        let result = await permissionApi.getPermissionList();
        if(result && result.code == 20000){
          // console.log(result);
        this.menuPermissionList = result.data.children;
        this.expandKeys = [this.menuPermissionList[0].id];
        }
      } catch (error) {
        console.error(error);
      }
    },

    // 添加的dialog
    toAddPermission(row){
      this.dialogPermissionVisible = true
      console.log(row);
      this.permission.pid = row.id; //父权限数据的id
      this.permission.level = (row.level + 1)
      this.permission.type = this.permission.level=== 4 ? 2 : 1
      // 清除校验(必须在界面更新之后)
      this.$nextTick(() => this.$refs.permission.clearValidate());
    },
    
    //根据选择的级别得到想要展示的dialog的标题
    getAddTitle(level) {
      if (level === 1 || level === 2) {
        return "添加菜单";
      } else if (level === 3) {
        return "添加功能";
      }
    },

    // 编辑的dialog
    toUpdatePermission(row){
      this.dialogPermissionVisible = true
      // console.log(row);
      this.permission = {...row}; 
      // 如果层级等于4，type == 2 否则type 就是1
      this.permission.type = this.permission.level === 4 ? 2 : 1
      // 清除校验(必须在界面更新之后)
      this.$nextTick(() => this.$refs.permission.clearValidate());
    },

    // 点击确定保存
    addOrUpdatePermission(){
      //表单校验
      this.$refs.permission.validate(async(valid)=>{
        if(valid){
          try {
            if(this.permission.id){//编辑
              await permissionApi.updatePermission(this.permission)
              Message.success('修改成功')
            }else{//添加
              await permissionApi.addPermission(this.permission)
              Message.success('添加成功')
            }
            //重置数据
            this.resetData()
            //刷新页面
            this.fetchPermissionList()
          } catch (error) {
            console.error(error);
            Message.error('失败')
          }
        }else{
          Message.error('请输入正确的格式')
        }
      })
      
    },

    // 删除某个权限节点
    removePermission(permission){
     this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await permissionApi.removePermission(permission.id)
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
        // 刷新页面
        this.fetchPermissionList();
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },


    // 重置数据
    resetData(){
      this.dialogPermissionVisible = false;
      this.permission = {
        level: 0,
        name: "",
        code: "",
        toCode: "",
      }
    }
  },
  mounted() {
    this.fetchPermissionList();
  },
};
</script>

<style scoped></style>